package com.example.community.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Controller
@RequestMapping("/alpha")
public class AlphaController {


    //响应post请求
    @RequestMapping(path="/student", method = RequestMethod.POST)
    @ResponseBody
    public String saveStudent(String name, int age){
        //参数名称和表单中的名称一致的时候可以这样直接获取
        System.out.println(name);
        System.out.println(age);
        return "success";
    }

    //响应html数据
    @RequestMapping(path="/teacher", method = RequestMethod.GET)
    public ModelAndView getTeacher(){
        ModelAndView mav = new ModelAndView();
        mav.addObject("name", "张三");
        mav.addObject("age", 30);
        mav.setViewName("/demo/view");
        return mav;//不常用
    }
    @RequestMapping(path="/school", method = RequestMethod.GET)
    public String getSchool(Model model){
        //DispatcherServlet在调用方法的时候, 看到model会自动实例化一个model对象
        model.addAttribute("name", "北京大学");
        model.addAttribute("age", 120);
        return "/demo/view";
        //一般都是使用这种方式, 返回的确实是string, 但是会被解析为路径
    }

    //响应json数据, 通常在异步请求中
    @RequestMapping(path="/emp", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getEmp(){
        //DispatcherServlet会根据@ResponseBody注解, 自动把我们返回的Map转为json字符串
        Map<String, Object> emp = new HashMap<>();
        emp.put("name", "张三");
        emp.put("age", 23);
        emp.put("salary", 8000.00);
        return emp;
    }

    @RequestMapping(path="/emps", method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> getEmps(){
        List<Map<String, Object>> list = new ArrayList<>();

        Map<String, Object> emp1 = new HashMap<>();
        emp1.put("name", "张三");
        emp1.put("age", 23);
        emp1.put("salary", 8200.00);
        Map<String, Object> emp2 = new HashMap<>();
        emp2.put("name", "张2");
        emp2.put("age", 23);
        emp2.put("salary", 8220.00);
        Map<String, Object> emp3 = new HashMap<>();
        emp3.put("name", "张1");
        emp3.put("age", 23);
        emp3.put("salary", 8222.00);
        list.add(emp1);
        list.add(emp2);
        list.add(emp3);
        return list;
    }
}
